package com.dream.wukong.bigdata.demo;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.*;

import java.io.IOException;
import java.util.Iterator;
import java.util.StringTokenizer;

/**
 * @Author: wuyichao
 * @Description:
 * @Date: Created in 17:20 2018/9/27.
 * @Modified:
 */
public class WordCount {

    public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {

        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();

        @Override
        public void map(LongWritable longWritable, Text text, OutputCollector<Text, IntWritable> outputCollector, Reporter reporter) throws IOException {


            String line = text.toString();

            StringTokenizer tokenizer = new StringTokenizer(line);

            while (tokenizer.hasMoreTokens()){
                word.set(tokenizer.nextToken());
                outputCollector.collect(word,one);
            }
        }
    }


    public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable>{

        @Override
        public void reduce(Text text, Iterator<IntWritable> iterator, OutputCollector<Text, IntWritable> outputCollector, Reporter reporter) throws IOException {
            int sum = 0;

            while (iterator.hasNext()){
                sum += iterator.next().get();
            }

            outputCollector.collect(text, new IntWritable(sum));
        }
    }

    public void job() throws IOException {

        /**
         JobConf：map/reduce的job配置类，向hadoop框架描述map-reduce执行的工作
         构造方法：JobConf()、JobConf(Class exampleClass)、JobConf(Configuration conf)等
        */
        JobConf conf = new JobConf(WordCount.class);
        conf.setUser("root");
        conf.setJobName("wordcount");   //设置一个用户定义的job名称
        conf.setOutputKeyClass(Text.class);  //为job的输出数据设置Key类
        conf.setOutputValueClass(IntWritable.class);   //为job输出设置value类
        conf.setMapperClass(Map.class);         //为job设置Mapper类
        conf.setCombinerClass(Reduce.class);      //为job设置Combiner类
        conf.setReducerClass(Reduce.class);        //为job设置Reduce类
        conf.setInputFormat(TextInputFormat.class);    //为map-reduce任务设置InputFormat实现类

        conf.setOutputFormat(TextOutputFormat.class);  //为map-reduce任务设置OutputFormat实现类

        FileInputFormat.setInputPaths(conf, "hdfs://172.16.52.46:9000/wuyichao/");

        FileOutputFormat.setOutputPath(conf, new Path("hdfs://172.16.52.46:9000/SpringHDFS/out"));
        JobClient.runJob(conf);         //运行一个job
    }
}